namespace SubSonic
{
    using SubSonic.Utilities;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Common;
    using System.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    public class Scaffold : Control, INamingContainer
    {
        private string _buttonCssClass;
        private string _editTableCssClass;
        private string _editTableItemCaptionCellCssClass;
        private string _editTableItemCssClass;
        private string _editTableLabelCssClass;
        private readonly List<string> _hiddenEditorColumnList = new List<string>();
        private readonly List<string> _hiddenGridColumnList = new List<string>();
        private string _manyToManyMap;
        [Bindable(true), DefaultValue(""), Category("Data")]
        private string _providerName;
        private readonly List<string> _readOnlyColumnList = new List<string>();
        private bool _showScaffoldCaption = true;
        private string _textBoxCssClass;
        private readonly Button btnAdd = new Button();
        private readonly Button btnCancel = new Button();
        private readonly Button btnDelete = new Button();
        private readonly Button btnSave = new Button();
        private string deleteConfirm = "Delete this record? This action cannot be undone...";
        private readonly System.Web.UI.WebControls.GridView grid = new System.Web.UI.WebControls.GridView();
        private readonly Label lblSorter = new Label();
        private const string ORDER_BY = "ORDER_BY";
        private const string SCAFFOLD_MODE = "SCAFFOLD_MODE";
        private TableSchema.Table schema;
        private const string SORT_DIRECTION = "SORT_DIRECTION";
        private readonly Panel surroundingPanel = new Panel();
        private string tableName = string.Empty;

        private void AddManyToMany(bool isEdit, HtmlTable tbl)
        {
            string[] strArray = this._manyToManyMap.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (strArray.Length > 0)
            {
                foreach (string str in strArray)
                {
                    TableSchema.Table table = Query.BuildTableSchema(str, this.ProviderName);
                    foreach (TableSchema.TableColumn column in table.Columns)
                    {
                        if (!column.IsPrimaryKey || !(column.ColumnName.ToLower() != this.schema.PrimaryKey.ColumnName.ToLower()))
                        {
                            continue;
                        }
                        string str2 = DataService.GetForeignKeyTableName(column.ColumnName, str, this.ProviderName);
                        if (string.IsNullOrEmpty(str2) || !isEdit)
                        {
                            continue;
                        }
                        CheckBoxList control = new CheckBoxList();
                        control.ID = str;
                        this.AddRow(tbl, Utility.ParseCamelToProper(str), control);
                        control.RepeatColumns = 2;
                        TableSchema.Table table2 = Query.BuildTableSchema(str2);
                        IDataReader reader = new Query(table2).ExecuteReader();
                        while (reader.Read())
                        {
                            control.Items.Add(new ListItem(reader[1].ToString(), reader[0].ToString()));
                        }
                        reader.Close();
                        reader = new Query(table).AddWhere(this.schema.PrimaryKey.ColumnName, this.PrimaryKeyValue).ExecuteReader();
                    Label_01DD:
                        while (reader.Read())
                        {
                            string str3 = reader[table2.PrimaryKey.ColumnName].ToString();
                            foreach (ListItem item in control.Items)
                            {
                                if (item.Value.ToLower().Equals(str3.ToLower()))
                                {
                                    item.Selected = true;
                                    goto Label_01DD;
                                }
                            }
                        }
                        reader.Close();
                    }
                }
            }
        }

        private void AddRow(HtmlTable tbl, string text, int colspan)
        {
            HtmlTableRow row = new HtmlTableRow();
            tbl.Rows.Add(row);
            HtmlTableCell cell = new HtmlTableCell();
            row.Cells.Add(cell);
            ApplyCssClass(cell, this.EditTableLabelCssClass);
            if (colspan > 0)
            {
                cell.ColSpan = colspan;
            }
            cell.InnerHtml = text;
        }

        private void AddRow(HtmlTable tbl, string cellValue1, Control control)
        {
            HtmlTableRow row = new HtmlTableRow();
            tbl.Rows.Add(row);
            HtmlTableCell cell = new HtmlTableCell();
            row.Cells.Add(cell);
            ApplyCssClass(cell, this.EditTableItemCaptionCellCssClass);
            cell.InnerHtml = "<b>" + cellValue1 + "</b>";
            HtmlTableCell cell2 = new HtmlTableCell();
            row.Cells.Add(cell2);
            ApplyCssClass(cell, this.EditTableItemCssClass);
            cell2.Controls.Add(control);
        }

        private static void ApplyCssClass(HtmlControl control, string cssClass)
        {
            if (!string.IsNullOrEmpty(cssClass))
            {
                control.Attributes.Add("class", cssClass);
            }
        }

        private static void ApplyCssClass(WebControl control, string cssClass)
        {
            if (!string.IsNullOrEmpty(cssClass))
            {
                control.CssClass = cssClass;
            }
        }

        private void BindEditor(TableSchema.Table tbl, string keyID)
        {
            Query query = new Query(tbl);
            query.AddWhere(tbl.PrimaryKey.ColumnName, keyID);
            IDataReader reader = query.ExecuteReader();
            if (reader.Read())
            {
                foreach (TableSchema.TableColumn column in tbl.Columns)
                {
                    if (column.IsPrimaryKey)
                    {
                        Control control = this.FindControl("pkID");
                        if (control != null)
                        {
                            string str = reader[column.ColumnName].ToString();
                            Type type = control.GetType();
                            if (type == typeof(Label))
                            {
                                ((Label) control).Text = str;
                            }
                            else if (type == typeof(DropDownList))
                            {
                                ((DropDownList) control).SelectedValue = str;
                            }
                            else if (type == typeof(TextBox))
                            {
                                ((TextBox) control).Text = str;
                            }
                        }
                        continue;
                    }
                    Control control2 = this.FindControl(column.ColumnName);
                    if (control2 != null)
                    {
                        Type type2 = control2.GetType();
                        if (type2 == typeof(TextBox))
                        {
                            TextBox box = (TextBox) control2;
                            box.Text = reader[column.ColumnName].ToString();
                            continue;
                        }
                        if (type2 == typeof(CheckBox))
                        {
                            if (!column.IsNullable || (column.IsNullable && (reader[column.ColumnName] != DBNull.Value)))
                            {
                                ((CheckBox) control2).Checked = Convert.ToBoolean(reader[column.ColumnName]);
                            }
                            continue;
                        }
                        if (type2 == typeof(DropDownList))
                        {
                            ((DropDownList) control2).SelectedValue = reader[column.ColumnName].ToString();
                        }
                        else
                        {
                            if (type2 == typeof(CalendarControl))
                            {
                                DateTime time;
                                if (DateTime.TryParse(reader[column.ColumnName].ToString(), out time))
                                {
                                    CalendarControl control3 = (CalendarControl) control2;
                                    control3.SelectedDate = new DateTime?(time.Date);
                                }
                                continue;
                            }
                            if (type2 == typeof(Label))
                            {
                                ((Label) control2).Text = reader[column.ColumnName].ToString();
                            }
                        }
                    }
                }
            }
        }

        private void BindGrid(string orderBy)
        {
            if ((this.schema != null) && (this.schema.PrimaryKey != null))
            {
                Query query = new Query(this.schema);
                string str = null;
                if (!string.IsNullOrEmpty(orderBy))
                {
                    str = orderBy;
                }
                else if (this.ViewState["ORDER_BY"] != null)
                {
                    str = (string) this.ViewState["ORDER_BY"];
                }
                int num = -1;
                if (!string.IsNullOrEmpty(str))
                {
                    this.ViewState.Add("ORDER_BY", str);
                    TableSchema.TableColumn col = this.schema.GetColumn(str);
                    if (col == null)
                    {
                        for (int j = 0; j < this.schema.Columns.Count; j++)
                        {
                            TableSchema.TableColumn column2 = this.schema.Columns[j];
                            if (column2.IsForeignKey && !string.IsNullOrEmpty(column2.ForeignKeyTableName))
                            {
                                TableSchema.Table table = DataService.GetSchema(column2.ForeignKeyTableName, this.ProviderName, TableType.Table);
                                if (table != null)
                                {
                                    col = table.Columns[1];
                                    num = j;
                                    break;
                                }
                            }
                        }
                    }
                    if ((col != null) && (col.MaxLength < 0x800))
                    {
                        if ((this.ViewState["SORT_DIRECTION"] == null) || (((string) this.ViewState["SORT_DIRECTION"]) == " ASC"))
                        {
                            if (num > -1)
                            {
                                query.OrderBy = OrderBy.Asc(col, "J" + num);
                            }
                            else
                            {
                                query.OrderBy = OrderBy.Asc(col);
                            }
                            this.ViewState["SORT_DIRECTION"] = " ASC";
                        }
                        else
                        {
                            if (num > -1)
                            {
                                query.OrderBy = OrderBy.Desc(col, "J" + num);
                            }
                            else
                            {
                                query.OrderBy = OrderBy.Desc(col);
                            }
                            this.ViewState["SORT_DIRECTION"] = " DESC";
                        }
                    }
                }
                DataTable table2 = query.ExecuteJoinedDataSet().Tables[0];
                this.grid.DataSource = table2;
                this.grid.AutoGenerateColumns = false;
                this.grid.Columns.Clear();
                this.grid.DataKeyNames = new string[] { this.schema.PrimaryKey.ColumnName };
                CommandField field = new CommandField();
                field.ShowEditButton = true;
                field.EditText = "Edit";
                this.grid.Columns.Insert(0, field);
                for (int i = 0; i < this.schema.Columns.Count; i++)
                {
                    BoundField field2 = new BoundField();
                    field2.DataField = table2.Columns[i].ColumnName;
                    field2.SortExpression = table2.Columns[i].ColumnName;
                    field2.HtmlEncode = false;
                    if (this.schema.Columns[i].IsForeignKey)
                    {
                        TableSchema.Table foreignKeyTable;
                        if (this.schema.Columns[i].ForeignKeyTableName == null)
                        {
                            foreignKeyTable = DataService.GetForeignKeyTable(this.schema.Columns[i], this.schema);
                        }
                        else
                        {
                            foreignKeyTable = DataService.GetSchema(this.schema.Columns[i].ForeignKeyTableName, this.ProviderName, TableType.Table);
                        }
                        if (foreignKeyTable != null)
                        {
                            field2.HeaderText = foreignKeyTable.DisplayName;
                        }
                    }
                    else
                    {
                        field2.HeaderText = this.schema.Columns[i].DisplayName;
                    }
                    if (!Utility.IsAuditField(table2.Columns[i].ColumnName) && !this._hiddenGridColumnList.Contains(table2.Columns[i].ColumnName.ToLower()))
                    {
                        this.grid.Columns.Add(field2);
                    }
                }
                this.grid.DataBind();
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            this.Mode = ScaffoldMode.Add;
            this.CreateChildControls();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.Mode = ScaffoldMode.List;
            this.CreateChildControls();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string text;
            if (!this.CanDelete)
            {
                throw new SecurityException(string.Format("This row can not be deleted as it has {0} read-only fields", this._readOnlyColumnList.Count));
            }
            if (this.schema.PrimaryKey.AutoIncrement || (this.schema.PrimaryKey.DataType == DbType.Guid))
            {
                text = ((Label) this.FindControl("pkID")).Text;
            }
            else
            {
                text = ((TextBox) this.FindControl("pkID")).Text;
            }
            Query query = new Query(this.schema);
            query.AddWhere(this.schema.PrimaryKey.ColumnName, text);
            DataService.ExecuteQuery(query.BuildDeleteCommand());
            this.Mode = ScaffoldMode.List;
            this.CreateChildControls();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.SaveEditor();
                this.Mode = ScaffoldMode.List;
                this.CreateChildControls();
            }
            catch (DbException exception)
            {
                this.ShowMessage("<font color=\"#990000\"><b>" + exception.Message + "</b></font>");
            }
        }

        private string BuildInsertSql()
        {
            string str = "INSERT INTO " + Utility.QualifyTableName(this.schema.SchemaName, this.schema.TableName, this.schema.Provider);
            string str2 = string.Empty;
            string str3 = string.Empty;
            foreach (TableSchema.TableColumn column in this.schema.Columns)
            {
                if ((((column.DataType != DbType.Binary) && (column.DataType != DbType.Byte)) && !column.AutoIncrement) && (!column.IsPrimaryKey || (column.DataType != DbType.Guid)))
                {
                    str2 = str2 + column.ColumnName + ",";
                    str3 = str3 + this.Prefix(column.ColumnName) + ",";
                }
            }
            str2 = str2.Remove(str2.Length - 1, 1);
            str3 = str3.Remove(str3.Length - 1, 1);
            string str4 = str;
            return (str4 + "(" + str2 + ") VALUES (" + str3 + ")");
        }

        private string BuildUpdateSql()
        {
            string str = "UPDATE " + Utility.QualifyTableName(this.schema.SchemaName, this.schema.TableName, this.schema.Provider) + " SET ";
            foreach (TableSchema.TableColumn column in this.schema.Columns)
            {
                if (((column.DataType != DbType.Binary) && (column.DataType != DbType.Byte)) && Utility.IsWritableColumn(column))
                {
                    string str2 = str;
                    str = str2 + column.ColumnName + " = " + this.Prefix(column.ColumnName) + ",";
                }
            }
            string str3 = str.Remove(str.Length - 1, 1);
            return (str3 + " WHERE " + this.schema.PrimaryKey.ColumnName + " = " + this.Prefix(this.schema.PrimaryKey.ColumnName));
        }

        protected override void CreateChildControls()
        {
            if (!string.IsNullOrEmpty(this.TableName))
            {
                this.schema = DataService.GetSchema(this.tableName, this.ProviderName, TableType.Table);
                this.surroundingPanel.ID = "pnlSurround";
                this.Controls.Add(this.surroundingPanel);
                this.surroundingPanel.Controls.Clear();
                Label child = new Label();
                child.ID = "lblTitle";
                this.surroundingPanel.Controls.Add(child);
                child.Text = "<h2>" + this.schema.DisplayName + " Admin</h2>";
                child.Visible = this.ShowScaffoldCaption;
                Panel panel = new Panel();
                panel.ID = "pnlButtons";
                this.surroundingPanel.Controls.Add(panel);
                this.btnAdd.ID = "btnAdd";
                panel.Controls.Add(this.btnAdd);
                this.btnSave.ID = "btnSave";
                panel.Controls.Add(this.btnSave);
                this.btnCancel.ID = "btnCancel";
                panel.Controls.Add(this.btnCancel);
                this.btnDelete.ID = "btnDelete";
                panel.Controls.Add(this.btnDelete);
                foreach (Button button in panel.Controls)
                {
                    ApplyCssClass(button, this.ButtonCssClass);
                }
                this.btnDelete.OnClientClick = "return CheckDelete();";
                this.btnSave.Text = "Save";
                this.btnDelete.Text = "Delete";
                this.btnCancel.Text = "Return";
                this.btnAdd.Text = "Add";
                this.btnAdd.Click += new EventHandler(this.btnAdd_Click);
                this.btnSave.Click += new EventHandler(this.btnSave_Click);
                this.btnCancel.Click += new EventHandler(this.btnCancel_Click);
                this.btnDelete.Click += new EventHandler(this.btnDelete_Click);
                this.btnDelete.Visible = this.CanDelete;
                bool flag = this.Mode == ScaffoldMode.Add;
                bool isEdit = this.Mode == ScaffoldMode.Edit;
                bool flag3 = this.Mode == ScaffoldMode.List;
                Panel panel2 = new Panel();
                panel2.ID = "pnlEditor";
                this.surroundingPanel.Controls.Add(panel2);
                this.CreateEditor(panel2, isEdit);
                Panel panel3 = new Panel();
                panel3.ID = "pnlGrid";
                this.surroundingPanel.Controls.Add(panel3);
                this.grid.ID = "grid";
                panel3.Controls.Add(this.grid);
                this.grid.Sorting += new GridViewSortEventHandler(this.grid_Sorting);
                this.grid.RowEditing += new GridViewEditEventHandler(this.grid_RowEditing);
                this.grid.AllowSorting = true;
                this.btnAdd.Visible = false;
                if (flag3)
                {
                    this.btnAdd.Visible = this.CanCreate;
                    panel2.Visible = false;
                    panel3.Visible = true;
                    this.btnSave.Visible = false;
                    this.btnCancel.Visible = false;
                    this.btnDelete.Visible = false;
                    this.BindGrid(string.Empty);
                }
                if (isEdit)
                {
                    panel2.Visible = true;
                    panel3.Visible = false;
                    this.BindEditor(this.schema, this.PrimaryKeyValue);
                    this.btnSave.Visible = true;
                    this.btnCancel.Visible = true;
                    this.btnDelete.Visible = this.CanDelete;
                }
                if (flag)
                {
                    panel2.Visible = true;
                    panel3.Visible = false;
                    this.btnSave.Visible = true;
                    this.btnCancel.Visible = true;
                    this.btnDelete.Visible = false;
                }
                Label label2 = new Label();
                label2.ID = "lblMessage";
                this.surroundingPanel.Controls.Add(label2);
                this.lblSorter.Text = string.Empty;
                this.surroundingPanel.Controls.Add(this.lblSorter);
            }
            this.ViewState["SCAFFOLD_MODE"] = this.Mode;
            if (this.Mode != ScaffoldMode.Edit)
            {
                this.PrimaryKeyValue = "";
            }
        }

        private void CreateEditor(Control destination, bool isEdit)
        {
            HtmlTable child = new HtmlTable();
            if (this.isManyToMany())
            {
                child = this.CreateManyMapper();
                destination.Controls.Add(child);
            }
            else
            {
                destination.Controls.Add(child);
                child.Width = "600px";
                if (this.ShowScaffoldCaption)
                {
                    this.AddRow(child, "<h2>" + this.schema.DisplayName + " Editor</h2>", 2);
                }
                foreach (TableSchema.TableColumn column in this.schema.Columns)
                {
                    Control editControl = this.GetEditControl(column);
                    if (editControl != null)
                    {
                        string displayName = column.DisplayName;
                        this.AddRow(child, displayName, editControl);
                        if (this._hiddenEditorColumnList.Contains(column.ColumnName.ToLower()))
                        {
                            editControl.Parent.Parent.Visible = false;
                        }
                        if (editControl.GetType() == typeof(TextBox))
                        {
                            TextBox box = (TextBox) editControl;
                            if (box.TextMode == TextBoxMode.MultiLine)
                            {
                                int effectiveMaxLength = Utility.GetEffectiveMaxLength(column);
                                string str2 = (effectiveMaxLength - box.Text.Length).ToString();
                                string str3 = effectiveMaxLength.ToString();
                                box.Attributes.Add("onkeyup", string.Concat(new object[] { "return imposeMaxLength(event, this, ", str3, ", ", child.Rows.Count, ");" }));
                                box.Attributes.Add("onChange", string.Concat(new object[] { "return imposeMaxLength(event, this, ", str3, ", ", child.Rows.Count, ");" }));
                                LiteralControl control2 = new LiteralControl(string.Concat(new object[] { "<div style='padding: 2px;'><div style='float:left'>Characters Remaining:&nbsp;</div><div id=\"counter", child.Rows.Count, "\" style=\"visibility:hidden\">", str2, "</div></div>" }));
                                box.Parent.Controls.Add(control2);
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(this._manyToManyMap) && isEdit)
                {
                    this.AddManyToMany(isEdit, child);
                }
            }
        }

        private HtmlTable CreateManyMapper()
        {
            HtmlTable tbl = new HtmlTable();
            tbl.Width = "600px";
            if (this.ShowScaffoldCaption)
            {
                this.AddRow(tbl, "<h2>" + this.schema.DisplayName + " Map </h2>", 2);
            }
            foreach (TableSchema.TableColumn column in this.schema.Columns)
            {
                if (column.IsPrimaryKey)
                {
                    string tableName = DataService.GetForeignKeyTableName(column.ColumnName, this.schema.Name, this.ProviderName);
                    Query query = new Query(DataService.GetSchema(tableName, this.ProviderName, TableType.Table));
                    DropDownList control = new DropDownList();
                    control.ID = column.ColumnName;
                    this.AddRow(tbl, tableName, control);
                    IDataReader reader = query.ExecuteReader();
                    while (reader.Read())
                    {
                        control.Items.Add(new ListItem(reader[1].ToString(), reader[0].ToString()));
                    }
                    reader.Close();
                    continue;
                }
                Control editControl = this.GetEditControl(column);
                this.AddRow(tbl, Utility.ParseCamelToProper(column.ColumnName), editControl);
            }
            return tbl;
        }

        private Control GetEditControl(TableSchema.TableColumn col)
        {
            WebControl control = null;
            string stringA = col.ColumnName.ToLower();
            if (col.IsPrimaryKey)
            {
                if (col.AutoIncrement || (col.DataType == DbType.Guid))
                {
                    Label label = new Label();
                    label.ID = "pkID";
                    control = label;
                }
                else
                {
                    TextBox box = new TextBox();
                    box.ID = "pkID";
                    control = box;
                }
                goto Label_02ED;
            }
            if (col.IsForeignKey)
            {
                DropDownList list = new DropDownList();
                TableSchema.Table tbl = DataService.GetSchema(DataService.GetForeignKeyTableName(col.ColumnName, col.Table.Name, this.ProviderName), this.ProviderName, TableType.Table);
                Query query = new Query(tbl);
                query.OrderBy = OrderBy.Asc(tbl.Columns[1].ColumnName);
                IDataReader reader = query.ExecuteReader();
                if (col.IsNullable)
                {
                    ListItem item = new ListItem("(Not Specified)", string.Empty);
                    list.Items.Add(item);
                }
                while (reader.Read())
                {
                    ListItem item2 = new ListItem(reader[1].ToString(), reader[0].ToString());
                    list.Items.Add(item2);
                }
                reader.Close();
                control = list;
            }
            else
            {
                switch (col.DataType)
                {
                    case DbType.AnsiString:
                    case DbType.Guid:
                    case DbType.Object:
                    case DbType.String:
                    case DbType.AnsiStringFixedLength:
                    case DbType.StringFixedLength:
                    case DbType.Xml:
                        if (!Utility.IsMatch(stringA, "CreatedBy") && !Utility.IsMatch(stringA, "ModifiedBy"))
                        {
                            TextBox box2 = new TextBox();
                            if (Utility.GetEffectiveMaxLength(col) > 250)
                            {
                                box2.TextMode = TextBoxMode.MultiLine;
                                box2.Columns = 60;
                                box2.Rows = 4;
                            }
                            else
                            {
                                box2.Width = Unit.Pixel(250);
                                if (stringA.EndsWith("guid"))
                                {
                                    box2.Text = Guid.NewGuid().ToString();
                                    box2.Enabled = false;
                                }
                            }
                            control = box2;
                        }
                        else
                        {
                            control = new Label();
                        }
                        goto Label_02DE;

                    case DbType.Binary:
                    case DbType.Byte:
                        goto Label_02DE;

                    case DbType.Boolean:
                    {
                        CheckBox box3 = new CheckBox();
                        if (Utility.IsMatch(stringA, "IsActive"))
                        {
                            box3.Checked = true;
                        }
                        if (Utility.IsMatch(stringA, "Deleted") || Utility.IsMatch(stringA, "IsDeleted"))
                        {
                            box3.Checked = false;
                        }
                        control = box3;
                        goto Label_02DE;
                    }
                    case DbType.Currency:
                    case DbType.Decimal:
                    case DbType.Double:
                    case DbType.Int16:
                    case DbType.Int32:
                    case DbType.Int64:
                    case DbType.Single:
                    case DbType.UInt16:
                    case DbType.UInt32:
                    case DbType.UInt64:
                    case DbType.VarNumeric:
                    {
                        TextBox box4 = new TextBox();
                        box4.Width = Unit.Pixel(50);
                        control = box4;
                        goto Label_02DE;
                    }
                    case DbType.Date:
                    case DbType.DateTime:
                    case DbType.Time:
                        if (!Utility.IsMatch(stringA, "ModifiedOn") && !Utility.IsMatch(stringA, "CreatedOn"))
                        {
                            control = new CalendarControl();
                        }
                        else
                        {
                            control = new Label();
                        }
                        goto Label_02DE;
                }
                control = new TextBox();
            }
        Label_02DE:
            if (control != null)
            {
                control.ID = col.ColumnName;
            }
        Label_02ED:
            if (control is TextBox)
            {
                TextBox box5 = (TextBox) control;
                ApplyCssClass(box5, this.TextBoxCssClass);
                if (control.GetType() == typeof(TextBox))
                {
                    int effectiveMaxLength = Utility.GetEffectiveMaxLength(col);
                    if (effectiveMaxLength > 0)
                    {
                        box5.MaxLength = effectiveMaxLength;
                    }
                }
            }
            if ((control != null) && this._readOnlyColumnList.Contains(stringA))
            {
                control.Enabled = false;
            }
            return control;
        }

        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.PrimaryKeyValue = this.grid.DataKeys[e.NewEditIndex].Value.ToString();
            this.Mode = ScaffoldMode.Edit;
            this.CreateChildControls();
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            if ((this.ViewState["SORT_DIRECTION"] == null) || (((string) this.ViewState["SORT_DIRECTION"]) == " ASC"))
            {
                this.ViewState["SORT_DIRECTION"] = " DESC";
            }
            else
            {
                this.ViewState["SORT_DIRECTION"] = " ASC";
            }
            this.Mode = ScaffoldMode.List;
            this.BindGrid(sortExpression);
        }

        private bool isManyToMany()
        {
            int num = 0;
            bool flag = false;
            foreach (TableSchema.TableColumn column in this.schema.Columns)
            {
                if (column.IsPrimaryKey)
                {
                    num++;
                }
            }
            if (num > 1)
            {
                flag = true;
            }
            return flag;
        }

        private string Prefix(string param)
        {
            return Utility.PrefixParameter(param, this.schema.Provider);
        }

        private void SaveEditor()
        {
            string text;
            QueryCommand cmd = new QueryCommand(string.Empty, this.ProviderName);
            if (this.schema.PrimaryKey.AutoIncrement || (this.schema.PrimaryKey.DataType == DbType.Guid))
            {
                text = ((Label) this.FindControl("pkID")).Text;
            }
            else
            {
                text = ((TextBox) this.FindControl("pkID")).Text;
            }
            if (this.Mode == ScaffoldMode.Edit)
            {
                cmd.CommandSql = this.BuildUpdateSql();
                cmd.Parameters.Add(this.Prefix(this.schema.PrimaryKey.ColumnName), text);
            }
            else
            {
                cmd.CommandSql = this.BuildInsertSql();
                if (!this.schema.PrimaryKey.AutoIncrement && (this.schema.PrimaryKey.DataType != DbType.Guid))
                {
                    cmd.Parameters.Add(this.Prefix(this.schema.PrimaryKey.ColumnName), text);
                }
            }
            if (this.schema != null)
            {
                bool isAdd = this.Mode == ScaffoldMode.Add;
                foreach (TableSchema.TableColumn column in this.schema.Columns)
                {
                    if (((column.DataType != DbType.Binary) && (column.DataType != DbType.Byte)) && !column.IsPrimaryKey)
                    {
                        Control ctrl = this.FindControl(column.ColumnName);
                        object obj2 = Utility.GetDefaultControlValue(column, ctrl, isAdd, true);
                        if (!column.AutoIncrement)
                        {
                            cmd.Parameters.Add(this.Prefix(column.ColumnName), obj2, column.DataType);
                        }
                    }
                }
            }
            DataService.ExecuteQuery(cmd);
            if (!string.IsNullOrEmpty(this._manyToManyMap))
            {
                foreach (string str2 in this._manyToManyMap.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    this.SaveManyToMany(str2);
                }
            }
        }

        private void SaveManyToMany(string mapTableName)
        {
            TableSchema.Table table = Query.BuildTableSchema(mapTableName);
            string columnName = string.Empty;
            foreach (TableSchema.TableColumn column in table.Columns)
            {
                if (column.IsPrimaryKey && (column.ColumnName.ToLower() != this.schema.PrimaryKey.ColumnName.ToLower()))
                {
                    columnName = column.ColumnName;
                    break;
                }
            }
            if (!string.IsNullOrEmpty(columnName))
            {
                int paramValue = Convert.ToInt32(this.PrimaryKeyValue);
                QueryCommandCollection commands = new QueryCommandCollection();
                Query query = new Query(DataService.GetSchema(mapTableName, this.ProviderName, TableType.Table));
                query.QueryType = QueryType.Delete;
                query.AddWhere(this.schema.PrimaryKey.ColumnName, paramValue);
                commands.Add(query.BuildDeleteCommand());
                string sql = "INSERT INTO " + mapTableName + "(" + columnName + "," + this.schema.PrimaryKey.ColumnName + ") VALUES (" + this.Prefix("fk") + "," + this.Prefix("pk)");
                CheckBoxList list = (CheckBoxList) this.FindControl(table.Name);
                if (list != null)
                {
                    foreach (ListItem item in list.Items)
                    {
                        if (item.Selected)
                        {
                            QueryCommand command = new QueryCommand(sql, this.ProviderName);
                            command.Parameters.Add(this.Prefix("fk"), item.Value, DbType.Int32);
                            command.Parameters.Add(this.Prefix("pk"), paramValue);
                            commands.Add(command);
                        }
                    }
                }
                DataService.ExecuteTransaction(commands);
            }
        }

        private void ShowMessage(string message)
        {
            Label label = (Label) this.FindControl("lblMessage");
            if (label != null)
            {
                label.Text = string.Concat(new object[] { message, " <br><i>", DateTime.Now, "</i>" });
            }
        }

        [Bindable(true), Description("Sets the CSS class used by all buttons."), DefaultValue("scaffoldButton"), Category("Display")]
        public string ButtonCssClass
        {
            get
            {
                return this._buttonCssClass;
            }
            set
            {
                this._buttonCssClass = value;
            }
        }

        private bool CanCreate
        {
            get
            {
                return (this._readOnlyColumnList.Count == 0);
            }
        }

        private bool CanDelete
        {
            get
            {
                return (this._readOnlyColumnList.Count == 0);
            }
        }

        [Bindable(true), Category("Display"), DefaultValue("scaffoldWrapper"), Description("Sets the CSS class for the div surrounding the scaffold.")]
        public string CssClass
        {
            get
            {
                return this.surroundingPanel.CssClass;
            }
            set
            {
                this.surroundingPanel.CssClass = value;
            }
        }

        [Bindable(true), DefaultValue("Delete this record? This action cannot be undone..."), Category("Behavior")]
        public string DeleteConfirm
        {
            get
            {
                return this.deleteConfirm;
            }
            set
            {
                this.deleteConfirm = value;
            }
        }

        [Description("Sets the CSS class used by the HTML table in the edit form."), DefaultValue("scaffoldEditTable"), Category("Display"), Bindable(true)]
        public string EditTableCssClass
        {
            get
            {
                return this._editTableCssClass;
            }
            set
            {
                this._editTableCssClass = value;
            }
        }

        [DefaultValue("scaffoldEditItemCaption"), Bindable(true), Description("Sets the CSS class used by the table cell surrounding edit item captions in the edit form."), Category("Display")]
        public string EditTableItemCaptionCellCssClass
        {
            get
            {
                return this._editTableItemCaptionCellCssClass;
            }
            set
            {
                this._editTableItemCaptionCellCssClass = value;
            }
        }

        [Description("Sets the CSS class used by editable form field elements in the edit form."), DefaultValue("scaffoldEditItem"), Category("Display"), Bindable(true)]
        public string EditTableItemCssClass
        {
            get
            {
                return this._editTableItemCssClass;
            }
            set
            {
                this._editTableItemCssClass = value;
            }
        }

        [Bindable(true), DefaultValue("scaffoldEditTableLabel"), Category("Display"), Description("Sets the CSS class used by the table label in the edit form.")]
        public string EditTableLabelCssClass
        {
            get
            {
                return this._editTableLabelCssClass;
            }
            set
            {
                this._editTableLabelCssClass = value;
            }
        }

        public System.Web.UI.WebControls.GridView GridView
        {
            get
            {
                return this.grid;
            }
        }

        [Category("Display"), Description("Sets the skin for GridView."), DefaultValue("scaffold"), Bindable(true)]
        public string GridViewSkinID
        {
            get
            {
                return this.grid.SkinID;
            }
            set
            {
                this.grid.SkinID = value;
            }
        }

        [Bindable(true), Description("A comma delimited list of column names which are not displayed in the Editor."), DefaultValue(""), Category("Data")]
        public string HiddenEditorColumns
        {
            set
            {
                this._hiddenEditorColumnList.Clear();
                foreach (string str in Utility.Split(value))
                {
                    this._hiddenEditorColumnList.Add(str.ToLower());
                }
            }
        }

        [Bindable(true), Category("Data"), DefaultValue(""), Description("A comma delimited list of column names which will not be displayed in the GridView.")]
        public string HiddenGridColumns
        {
            set
            {
                this._hiddenGridColumnList.Clear();
                foreach (string str in Utility.Split(value))
                {
                    this._hiddenGridColumnList.Add(str.ToLower());
                }
            }
        }

        [Category("Data"), DefaultValue(""), Bindable(true)]
        public string ManyToManyMap
        {
            get
            {
                return this._manyToManyMap;
            }
            set
            {
                this._manyToManyMap = value;
            }
        }

        public ScaffoldMode Mode
        {
            get
            {
                if (this.ViewState["SCAFFOLD_MODE"] == null)
                {
                    this.ViewState["SCAFFOLD_MODE"] = ScaffoldMode.List;
                }
                return (ScaffoldMode) this.ViewState["SCAFFOLD_MODE"];
            }
            private set
            {
                this.ViewState["SCAFFOLD_MODE"] = value;
            }
        }

        public string PrimaryKeyValue
        {
            get
            {
                return (string) this.ViewState["PrimaryKeyValue"];
            }
            private set
            {
                this.ViewState["PrimaryKeyValue"] = value;
            }
        }

        public string ProviderName
        {
            get
            {
                return this._providerName;
            }
            set
            {
                this._providerName = value;
            }
        }

        [Description("A comma delimited list of column names which are read only."), Category("Data"), DefaultValue(""), Bindable(true)]
        public string ReadOnlyColumns
        {
            set
            {
                this._readOnlyColumnList.Clear();
                foreach (string str in Utility.Split(value))
                {
                    this._readOnlyColumnList.Add(str.ToLower());
                }
            }
        }

        [Bindable(true), Category("Display"), Description("If true, a scaffold caption will be shown")]
        public bool ShowScaffoldCaption
        {
            get
            {
                return this._showScaffoldCaption;
            }
            set
            {
                this._showScaffoldCaption = value;
            }
        }

        [Category("Data"), DefaultValue(""), Bindable(true)]
        public string TableName
        {
            get
            {
                return this.tableName;
            }
            set
            {
                this.tableName = value;
            }
        }

        [Description("Sets the CSS class used by all TextBox elements in the edit form."), DefaultValue("scaffoldTextBox"), Category("Display"), Bindable(true)]
        public string TextBoxCssClass
        {
            get
            {
                return this._textBoxCssClass;
            }
            set
            {
                this._textBoxCssClass = value;
            }
        }

        public enum ScaffoldMode
        {
            List,
            Add,
            Edit
        }
    }
}

